<template>
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-picker
      :columns="columns"
      :columns-field-names="customFieldName"
      @confirm="onConfirm"
      @cancel="showPicker = false"
    >
      <template #title>
        <span class="clear-btn" @click="handleClear"> 清空选择 </span>
      </template>
    </van-picker>
  </van-popup>
</template>

<script setup lang="ts">
import { useVModels } from '@vueuse/core'
import { ref, defineProps, defineEmits } from 'vue'
import { Sex, SexName } from '../types'

interface Column {
  name: SexName
  value: Sex
}

const props = defineProps<{
  show: boolean
  modelValue: string
  sexName: SexName | undefined
}>()

const emits = defineEmits([
  'update:show',
  'update:modelValue',
  'update:sexName',
])

const customFieldName = {
  text: 'name',
}

const columns = ref<Column[]>([
  {
    name: '男',
    value: Sex.boy,
  },
  {
    name: '女',
    value: Sex.girl,
  },
])

const {
  modelValue: value,
  show: showPicker,
  sexName,
} = useVModels(props, emits)

function onConfirm(item: Column) {
  value.value = item.value
  sexName.value = item.name
  showPicker.value = false
}

function handleClear() {
  showPicker.value = false
  value.value = ''
  sexName.value = undefined
}
</script>

<style lang="less" scoped>
.clear-btn {
  font-size: var(--van-picker-action-font-size);
}
</style>
